import { globalConfig } from '@/config/GlobalConfig.ts'
import { StorageManager } from '@/config/storage/StorageManager.ts'
import type { PiniaPluginContext } from 'pinia'

const localStorage = new StorageManager(globalConfig.storagePrefix, window.localStorage)
const sessionStorage = new StorageManager(globalConfig.storagePrefix, window.sessionStorage)

/**
 * 持久化插件
 */
export function PersistencePlugin(context: PiniaPluginContext): void {
    const { store, options } = context

    const { persistence, eternal, filter } = options?.persistencePlugin ?? {}
    if (!persistence) {
        return
    }

    const storage = eternal ? localStorage : sessionStorage

    const value = storage.getItem(store.$id)
    if (value) {
        store.$patch(value)
    }

    store.$subscribe((_, storeValue) => {
        console.debug('保存 Store ', store.$id)
        if (!!filter && typeof filter === 'function') {
            storage.setItem(store.$id, filter(storeValue))
        } else {
            storage.setItem(store.$id, storeValue)
        }
    }, { deep: true, immediate: true })

}


export interface PersistencePluginOption<S = any> {

    /**
     * 启用持久化
     */
    persistence?: boolean

    /**
     * 永久保存 指 `LocalStorage`
     */
    eternal?: boolean

    /**
     * 筛选 仅保存部分属性
     */
    filter?: (store: S) => any

}
